<template>
    <div class="row" v-for="(row, i) in  mine.mineList " :key="i">
        <div class="block col" :class="{
        'border-block unknow': !col.open,
        'boom': mine.boom && i == mine.boom[0] && j == mine.boom[1],
        'mine': mine.boom?.length && col.value && col.mark != 1,
        'active': mine.active.includes(i * mine.getLevel.width + j), 'mark': col.mark == 1, query: col.mark == 2
    }" :style="{ '--block-text-color': color[col.around] }" @contextmenu="(e) => { e.preventDefault() }"
            v-for="(col, j) in  row " :key="j" @mousedown.stop="setMine($event, i, j)" @mouseup.stop="mouseUp">
            {{ col.open ? col.around : '' }}
        </div>
    </div>
</template>

<script setup lang="ts">
import mineStore from '@/store/mine'
import { ref } from 'vue'
import { around, aroundMark } from '@/utils/mine'

const mine = mineStore()
const timer = ref()
const color = ref(['transparent', '#0000ff', '#008000', '#ff0000', '#000080', '#800000', '#008080', '#000000', '#808080'])

function setMine(e: MouseEvent, row: number, col: number) {
    e.preventDefault()
    if (mine.over) return
    mine.play = true
    // 鼠标左右键同时按下
    if (e.buttons == 3 && mine.mineList?.[row][col].open && mine.mineList?.[row][col].around) {
        timer.value && clearTimeout(timer.value)
        mine.active = around(mine.mineList!, row, col)
        if (!mine.active.length || mine.mineList?.[row][col].around <= aroundMark(mine.mineList!, row, col)) {
            for (let x = -1; x <= 1; x++) {
                for (let y = -1; y <= 1; y++) {
                    if (x || y) {
                        const ix = col + x, iy = row + y
                        if (mine.mineList?.[row][col].around < aroundMark(mine.mineList!, row, col) && ix >= 0 &&
                            ix < mine.getLevel.width && iy >= 0 && iy < mine.getLevel.height &&
                            mine.mineList?.[iy][ix].mark == 1 && !mine.mineList?.[iy][ix].value) {
                            mine.boom = [iy, ix]
                        } else if (ix >= 0 && ix < mine.getLevel.width && iy >= 0 && iy < mine.getLevel.height && mine.mineList?.[iy][ix].mark != 1) {
                            mine.openMine(iy, ix)
                        }
                    }
                }
            }
        }
        return
    }
    timer.value = setTimeout(() => {
        // if (!mine.over) {
        if (e.buttons === 1) {
            const isBoom = mine.openMine(row, col)
            if (isBoom == 'boom') {
                mine.boom = [row, col]
            }
        } else if (e.buttons === 2) {
            mine.markMine(row, col)
        }
        // }
    }, 100)
    // console.log(e.buttons, e.button)
    return
}
function mouseUp(e: MouseEvent) {
    e.preventDefault()
    mine.active = []
}
</script>

<style lang="scss" scoped>
.row {
    display: flex;
}
</style>